import React, {useCallback, useEffect, useState, useRef} from "react";
import { useCalculate } from "../../hooks/useCalculate";
import {FlatList, RefreshControl, StyleSheet, Text, TouchableOpacity, View,Platform} from "react-native";
import CalculateItem from "./CalculateItem";
import {ICalculate} from "../../types/calculate";
import LevelView from "../../components/Level";
import EmptyView from "../../components/EmptyView";
import Header from "../Home/Header";
import { useIsFocused } from '@react-navigation/native';
import {NativeBaseProvider} from "native-base";
import SkeletonView from "../../components/Skeleton";

export function CalculateList(props) {
    const isFocused = useIsFocused();
    const [dateTime, setDateTime] = useState([]);
    const [ selectLevelIndex, setSelectLevelIndex ] = useState(1);
    const [ selectPeriod, setSelectPeriod ] = useState(false);
    const [ titleName, setTitleName ] = useState('');
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const levelViewRef = useRef(null);
    const headerRef = useRef(null);
    const { calculates } = useCalculate();

    

    const [selectIndex,setselectIndex] = useState(1)
    const shadowStyle = Platform.select({
        ios: {
            shadowColor: 'black',
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.2,
            shadowRadius: 4,
        },
        android: {
            elevation: 2,
        },
    });
    let typeViewStyle = styles.percentItemView;
    let moodsViewStyle = styles.percentItemView;
    if (selectIndex === 1) {
        typeViewStyle = {
            ...typeViewStyle,
            backgroundColor: '#fff',
            ...shadowStyle,
        };
    } else {
        moodsViewStyle = {
            ...moodsViewStyle,
            backgroundColor: '#fff',
            ...shadowStyle,
        };
    }




    useEffect(() => {
        if (isFocused && dateTime.length > 0) {
            onRefresh();
        }
    },[isFocused]);

    const onRefresh = () => {
        setRefreshing(true);
        levelViewRef?.current?.refresh();
    }

    function renderItem({ item, }: { item: ICalculate }) {
        return (
            <CalculateItem
                {...item}
                selectIndex={selectIndex}
                selectLevelIndex={selectLevelIndex}
            />
        );
    }

    const onEndReached = () => {
        //todo 分页加载
    }

    const renderEmptyComponent = () => {
        return <EmptyView/>;
    }

    console.log('-----calculates----state--',calculates,'dateTime:',dateTime)

    return (
        <NativeBaseProvider >
            <View style={styles.container}>
                <Header
                    from={'calculate'}
                    ref={headerRef}
                    selectPeriod = {selectPeriod}
                    iconClick={()=>{
                        props.navigation.navigate('OverView',{title: titleName+'总览',dateTime: dateTime});
                    }}
                    selectedRangeCallback={(period)=>{
                        if (period.length === 2) {
                            setDateTime(period);
                            let newDateBeforeSevenDay = period[0].split('-');
                            newDateBeforeSevenDay.splice(0,1);
                            let newCurrentDay = period[1].split('-');
                            newCurrentDay.splice(0,1);
                            setSelectPeriod(true);
                            levelViewRef?.current?.loadSetDateTimeWithoutYear([newDateBeforeSevenDay.join('.'),newCurrentDay.join('.')]);
                            levelViewRef?.current?.loadCalculateData(period[0],period[1]);
                        }
                    }}
                    selectDateCallback = {(date)=>{
                        levelViewRef?.current?.reLoadTimeSlot(date);
                    }}
                    toggleModalCallback={()=>{
                        setSelectPeriod(false);
                    }}
                />

                <LevelView
                    from={'calculate'}
                    ref={levelViewRef}
                    selectPeriod={selectPeriod}
                    levelCallback={(index) => {
                        setSelectLevelIndex(index);
                    }}
                    periodCallback={(type) => {
                        setSelectPeriod(type);
                    }}
                    clickPeriodDate={() => {
                        setSelectPeriod(true);
                        setTimeout(()=>{
                            headerRef?.current?.toggleModal();
                        },10)
                    }}
                    titleCallback={(title) => {
                        setTitleName(title);
                    }}
                    dateCallback={(date)=>{
                        setDateTime(date);
                    }}
                    setLoading={(refreshing)=>{
                        setRefreshing(refreshing);
                        if (!refreshing && loading) {
                            setLoading(false);
                        }
                    }}
                />
                {
                    loading ? <SkeletonView/>
                        :
                        <FlatList
                            data={calculates}
                            style={{ flex: 1 }}
                            refreshControl={
                                <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={onRefresh}
                                    tintColor="rgba(67, 113, 177, 1)"
                                    // title="Loading..."
                                    // titleColor="rgba(198, 224, 247, 1)"
                                    // size={0}
                                    colors={["rgba(67, 113, 177, 1)"]}
                                    progressBackgroundColor="white"
                                />
                            }
                            onEndReached={onEndReached}
                            renderItem={renderItem}
                            keyExtractor={(item,index) => "calculate_"+index}
                            showsVerticalScrollIndicator={false}
                            ListEmptyComponent={renderEmptyComponent}
                            ListFooterComponent={()=>{
                                return <View style={{height:50}}></View>
                            }}
                        />
                }
                {
                    calculates && calculates.length
                    ?
                    <View style={{position:'absolute',bottom:0,flexDirection:'row',width:'100%',paddingHorizontal:18,justifyContent:"space-between"}}>
                        <View style = {[styles.percentTypeView,{width:"40%"}]}>
                            <TouchableOpacity
                                style={typeViewStyle}
                                onPress={() => setselectIndex(1)}
                            >
                                <Text style={[styles.circleTypeText,{fontWeight: selectIndex === 1 ? 'bold' : 'normal'}]}>24h</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={moodsViewStyle}
                                onPress={() => setselectIndex(2)}
                            >
                                <Text style={[styles.circleTypeText,{fontWeight: selectIndex === 2 ? 'bold' : 'normal'}]}>总计</Text>
                            </TouchableOpacity>
                        </View>
                        <View style = {[styles.percentTypeView,{backgroundColor:'#fff',width:'50%',paddingHorizontal:20,}]}>
                            <View style={{flexDirection:'row',alignItems:'center'}}>
                                <View style={{width:24,height:4,backgroundColor:'#E5E5EA',borderRadius:100,marginRight:8}}></View>
                                <Text style={{fontSize:14,color:'#2C2C2E',fontFamily:'HarmonyOS Sans SC'}}>预算</Text>
                            </View>
                            <View style={{flexDirection:'row',alignItems:'center'}}>
                                <View style={{width:24,height:4,backgroundColor:'#3076D9',borderRadius:100,marginRight:8}}></View>
                                <Text style={{fontSize:14,color:'#2C2C2E',fontFamily:'HarmonyOS Sans SC'}}>实际</Text>
                            </View>
                        </View>
                    </View>
                    :
                    ''
                }
                
            </View>
        </NativeBaseProvider>
    );
}


const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    percentTypeView: {
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 12,
        height: 36,
        borderRadius: 12,
        paddingHorizontal: 2,
        justifyContent: 'space-between',
        width: '40%',
        // flex:1,
        shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.2)', // 阴影颜色
        shadowOffset: { width: 0, height: 2 }, // 阴影偏移
        shadowOpacity: 1, // 阴影不透明度
        shadowRadius: 2, // 阴影半径
        elevation: 2, // 阴影深度
    },
    percentItemView: {
        width: '48%',
        height: 32,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
        backgroundColor: 'rgba(232, 232, 232, 1)'
    },
    circleTypeText: {
        color: 'rgba(44, 44, 46, 1)',
        fontSize: 14,
        fontFamily:'HarmonyOS Sans SC'
    },
});
